package com.x.provider.oss.service.impl;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ciModel.auditing.ImageAuditingRequest;
import com.qcloud.cos.model.ciModel.auditing.ImageAuditingResponse;
import com.qcloud.cos.model.ciModel.auditing.TextAuditingRequest;
import com.qcloud.cos.model.ciModel.auditing.TextAuditingResponse;
import com.qcloud.cos.region.Region;
import com.x.core.domain.SuggestionTypeEnum;
import com.x.core.utils.JsonUtil;
import com.x.provider.api.oss.enums.ContentGroupTypeEnum;
import com.x.provider.api.oss.enums.MimeTypeEnum;
import com.x.provider.api.oss.model.dto.green.AttributeGreenRequestDTO;
import com.x.provider.api.oss.model.dto.green.AttributeGreenResultDTO;
import com.x.provider.api.oss.model.dto.green.GreenRequestDTO;
import com.x.provider.oss.configure.QqConfig;
import com.x.provider.oss.model.bo.GreenContentRequestBO;
import com.x.provider.oss.service.ContentGreenService;
import com.x.provider.oss.service.GreenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;

import java.util.Map;

@Slf4j
@Service("tencentGreenService")
public class TencentGreenServiceImpl implements GreenService {

    private final ContentGreenService contentReviewService;
    private final QqConfig tencentOssConfig;

    public TencentGreenServiceImpl(ContentGreenService contentReviewService,
                                   QqConfig tencentOssConfig){
        this.contentReviewService = contentReviewService;
        this.tencentOssConfig = tencentOssConfig;
    }

    @Override
    public void onGreenResultNotify(Map<String, Object> result){
        log.info("green result notify, result:{}", JsonUtil.toJSONString(result));
        if((int)result.get("code") == 0){
            Map<String, Object> data = (Map<String, Object>)result.get("data");
            String url = (String) data.get("url");
            SuggestionTypeEnum suggestionTypeEnum = prepare((Integer) data.get("result"));
            String objectKey = url.substring(url.lastIndexOf(QqConfig.DOMAIN_QCLOUD) + QqConfig.DOMAIN_QCLOUD.length());
            contentReviewService.greenContent(GreenContentRequestBO.builder()
                    .contentGroup(ContentGroupTypeEnum.OSS.getValue())
                    .contentKey(objectKey)
                    .mimeType(MimeTypeEnum.NULL.name())
                    .suggestion(suggestionTypeEnum.name())
                    .build());
        } else{
            log.error("gren result error, error code:{}  error message:{}", result.get("code"), result.get("message"));
        }
    }

    @Override
    public SuggestionTypeEnum green(GreenRequestDTO greenRpcAO) {
        if (greenRpcAO.getDataType().equals(MimeTypeEnum.PICTURE.name())){
            return greenPicture(greenRpcAO);
        }
        if (greenRpcAO.getDataType().equals(MimeTypeEnum.TEXT.name())){
            return greenText(greenRpcAO);
        }
        return SuggestionTypeEnum.PASS;
    }

    private SuggestionTypeEnum greenPicture(GreenRequestDTO greenRpcAO) {
        COSClient cosClient = getCosClient();
        //1.创建任务请求对象
        ImageAuditingRequest request = new ImageAuditingRequest();
        //2.添加请求参数 参数详情请见api接口文档
        //2.1设置请求bucket
        request.setBucketName(tencentOssConfig.getOssBucketCustomer());
        //2.2设置审核类型
        request.setBizType(tencentOssConfig.getPictureGreenBiztype());
        //2.3设置bucket中的图片位置
        request.setObjectKey(greenRpcAO.getValue());
        //3.调用接口,获取任务响应对象
        ImageAuditingResponse response = cosClient.imageAuditing(request);

        return response.getResult().equals("1") ? SuggestionTypeEnum.BLOCK : SuggestionTypeEnum.PASS;
    }

    private SuggestionTypeEnum greenText(GreenRequestDTO greenRpcAO) {
        COSClient cosClient = getCosClient();
        //1.创建任务请求对象
        TextAuditingRequest request = new TextAuditingRequest();
        //2.添加请求参数 参数详情请见api接口文档
        //2.1设置请求bucket
        request.setBucketName(tencentOssConfig.getOssBucketCustomer());
        request.getInput().setContent(Base64Utils.encodeToString(greenRpcAO.getValue().getBytes()));
        request.getConf().setBizType(tencentOssConfig.getTextGreenBizType());
        //3.调用接口,获取任务响应对象
        TextAuditingResponse response = cosClient.createAuditingTextJobs(request);

        return response.getJobsDetail().getResult().equals("1") ? SuggestionTypeEnum.BLOCK : SuggestionTypeEnum.PASS;
    }


    @Override
    public AttributeGreenResultDTO greenAttributeSync(AttributeGreenRequestDTO attributeGreenRpcAO) {
        return null;
    }

    private SuggestionTypeEnum prepare(Integer greenResult){
        return greenResult == 0 ? SuggestionTypeEnum.PASS : SuggestionTypeEnum.BLOCK;
    }

    private COSClient getCosClient(){
        COSCredentials cred = new BasicCOSCredentials(tencentOssConfig.getAppSecretId(), tencentOssConfig.getAppSecretKey());
        // 2 设置 bucket 区域,详情请参阅 COS 地域 https://cloud.tencent.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region(QqConfig.AP_CHENGDU));
        // 3 生成 cos 客户端
        return new COSClient(cred, clientConfig);
    }
}
